//package com.ruoyi.common.utils.fabric;
//
//import lombok.extern.slf4j.Slf4j;
//import org.hyperledger.fabric.sdk.Channel;
//import org.hyperledger.fabric.sdk.ChannelConfiguration;
//import org.hyperledger.fabric.sdk.Enrollment;
//import org.hyperledger.fabric.sdk.Orderer;
//import org.hyperledger.fabric.sdk.Peer;
//import org.hyperledger.fabric.sdk.exception.CryptoException;
//import org.hyperledger.fabric.sdk.identity.X509Enrollment;
//
//import javax.xml.bind.DatatypeConverter;
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.nio.file.Files;
//import java.nio.file.Paths;
//import java.security.KeyFactory;
//import java.security.NoSuchAlgorithmException;
//import java.security.PrivateKey;
//import java.security.spec.InvalidKeySpecException;
//import java.security.spec.PKCS8EncodedKeySpec;
//import java.util.EnumSet;
//import java.util.Iterator;
//import java.util.Properties;
//import java.util.concurrent.TimeUnit;
//
//@Slf4j
//public class CreateChannel {
//    public void createChannel() {
//        try {
//            // 创建org1的用户管理员对象的创建
//            UserContextImp org1Admin = new UserContextImp();
//            // 秘钥地址
//            String pkPath = "application_java_admin/src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore";
//            File pkFile1 = new File(pkPath);
//            File[] pkFiles1 = pkFile1.listFiles();
//            // 证书地址
//            String certPath = "application_java_admin/src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts";
//            File certFile1 = new File(certPath);
//            File[] certFiles1 = certFile1.listFiles();
//            // 进行证书和秘钥的登记
//            Enrollment enrollment = getEnrollment(pkPath, pkFiles1[0].getName(), certPath, certFiles1[0].getName());
//            org1Admin.setEnrollment(enrollment);
//            org1Admin.setName("admin");
//            org1Admin.setMspId("Org1MSP");
//            org1Admin.setAffiliation("org1");
//            // org2的用户管理对象的创建
//            UserContextImp org2Admin = new UserContextImp();
//            String pkPath2 = "application_java_admin/src/main/resources/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore";
//            File pkFile2 = new File(pkPath2);
//            File[] pkFiles2 = pkFile2.listFiles();
//            String certPath2 = "application_java_admin/src/main/resources/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/signcerts";
//            File certFile2 = new File(certPath2);
//            File[] certFiles2 = certFile2.listFiles();
//            Enrollment enrollment1 = getEnrollment(pkPath2, pkFiles2[0].getName(), certPath2, certFiles2[0].getName());
//            org2Admin.setEnrollment(enrollment1);
//            org2Admin.setName("user2");
//            org2Admin.setMspId("Org2MSP");
//            org2Admin.setAffiliation("org2");
//
//            FabricClient fabricClient = new FabricClient(org1Admin);
////            Properties orderPro = new Properties();
//            // properties配置的信息导入
//            Properties orderPro = loadTLSFile(TestConfig.ORDERER_PEMFILE, TestConfig.ORDERER_CERT, TestConfig.ORDERER_KEY, TestConfig.ORDER_NAME, "OrdererMSP");
//            // 通过HFClient对象新建一个orderer对象,
//            Orderer orderer = fabricClient.getInstance().newOrderer("orderer.example.com", "grpcs://orderer.example.com:7050", orderPro);
//            // 创建通道配置对象,参数为创建的.tx通道文件
//            ChannelConfiguration channelConfiguration = new ChannelConfiguration(new File("application_java_admin/src/main/resources/channel1.tx"));
//
//            byte[] channelConfigurationSignatures = fabricClient.getInstance().getChannelConfigurationSignature(channelConfiguration, org1Admin);
//            // 新建一个channel
//            Channel channel1 = fabricClient.getInstance().newChannel("channel1", orderer, channelConfiguration, channelConfigurationSignatures);
////            Channel channel1 = fabricClient.getInstance().newChannel("mychannel");
//
//            for (Peer peer : channel1.getPeers()) {
//                System.out.println(peer.getName());
//            }
//            // 加载配置
//            Properties peer1Pro = loadTLSFile(TestConfig.PEER1_PEMFILE, TestConfig.PEER1_CERT, TestConfig.PEER1_KEY, TestConfig.PEER1_NAME, "Org1MSP");
//            //新建peer1
//            Peer peer0_Org1 = fabricClient.getInstance().newPeer(TestConfig.PEER1_NAME, "grpcs://192.168.127.130:7051", peer1Pro);
//
//            // 新建peer2
//            Properties peer2Pro = loadTLSFile(TestConfig.PEER2_PEMFILE, TestConfig.PEER2_CERT, TestConfig.PEER2_KEY, TestConfig.PEER2_NAME, "Org2MSP");
//            Peer peer0_Org2 = fabricClient.getInstance().newPeer(TestConfig.PEER2_NAME, "grpcs://192.168.127.130:9051", peer2Pro);
//
//            // 将peer加入到channel中
//            channel1.joinPeer(peer0_Org1, Channel.PeerOptions.createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)));
//            channel1.addOrderer(orderer);
//            // 进行判断,是否加入成功
////            assertFalse(channel1.getPeers(EnumSet.of(Peer.PeerRole.EVENT_SOURCE)).isEmpty());
////            assertFalse(channel1.getPeers(Peer.PeerRole.NO_EVENT_SOURCE).isEmpty());
//            // 进行初始化通道
//            channel1.initialize();
//            log.info("Channel created " + channel1.getName());
////                   切换为org2的用户进行上述操作,添加peer
//            fabricClient.getInstance().setUserContext(org2Admin);
//            channel1 = fabricClient.getInstance().getChannel("channel1");
//            channel1.joinPeer(peer0_Org2, Channel.PeerOptions.createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)));
//            Iterator<Peer> iterator = channel1.getPeers().iterator();
////            assertFalse(channel1.getPeers(EnumSet.of(Peer.PeerRole.EVENT_SOURCE)).isEmpty());
////            assertFalse(channel1.getPeers(PeerRole.NO_EVENT_SOURCE).isEmpty());
//            channel1.initialize();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    //    将配置项导入到配置pro中
//    private static Properties loadTLSFile(String servicePath, String certPath, String keyPath, String hostName, String Msp) throws IOException {
//        Properties properties = new Properties();
////    # 其实只需要一个TLS根证书就可以了，比如TLS相关的秘钥等都是可选的
//        properties.put("pemBytes", Files.readAllBytes(Paths.get(servicePath)));
//        properties.setProperty("clientCertFile", certPath);
//        properties.setProperty("clientKeyFile", keyPath);
//        properties.setProperty("sslProvider", "openSSL");
//        properties.setProperty("negotiationType", "TLS");
//        properties.setProperty("trustServerCertificate", "true");
//        properties.setProperty("hostnameOverride", hostName);
//        properties.setProperty("ssl-target-name-override", hostName);
//        if (hostName.contains("peer")) {
//            properties.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize", 9000000);
////            properties.setProperty("org.hyperledger.fabric.sdk.peer.organization_mspid", Msp);
//        }
//        if (hostName.contains("orderer")) {
//            properties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[]{5L, TimeUnit.MINUTES});
//            properties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[]{8L, TimeUnit.SECONDS});
//            properties.put("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls", new Object[]{true});
////            properties.setProperty("org.hyperledger.fabric.sdk.orderer.organization_mspid", Msp);
////
//        }
//        return properties;
//    }
//
//    // 证书和秘钥的登记过程
//    public static X509Enrollment getEnrollment(String keyFolderPath, String keyFileName, String certFolderPath, String certFileName)
//        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CryptoException {
//        PrivateKey key = null;
//        String certificate = null;
//        InputStream isKey = null;
//        BufferedReader brKey = null;
//        try {
//            isKey = new FileInputStream(keyFolderPath + File.separator + keyFileName);
//            brKey = new BufferedReader(new InputStreamReader(isKey));
//            StringBuilder keyBuilder = new StringBuilder();
//            for (String line = brKey.readLine(); line != null; line = brKey.readLine()) {
//                if (line.indexOf("PRIVATE") == -1) {
//                    keyBuilder.append(line);
//                }
//            }
//            certificate = new String(Files.readAllBytes(Paths.get(certFolderPath, certFileName)));
//            byte[] encoded = DatatypeConverter.parseBase64Binary(keyBuilder.toString());
//            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
//            KeyFactory kf = KeyFactory.getInstance("EC");
//            key = kf.generatePrivate(keySpec);
//        } finally {
//            isKey.close();
//            brKey.close();
//        }
//        X509Enrollment enrollment = new X509Enrollment(key, certificate);
//        return enrollment;
//    }
//}
